<?php

include_once 'AdminController.php';


class api extends AdminController{
	
	function __construct(){
		parent::__construct();
		include_once './index/include/Tools.php'; 
		include_once './index/config/api.config.php';
		include_once './index/config/wx.config.php';
	}
	
	
	function doServicePost2($service_name,$parm){
		//获取系统参数
		$sysparm = $this->initServiceParm($service_name);
		//合并系统参数与业务参数 	 
		$url = APIURL::_getServiceUrl();
		$data = json_decode(Tools::http_post2($url,$sysparm,$parm),true);
		return $data;
	}
	
	/**
	* 获取JS参数信息
	* @param String $url 当前页面地址
	* @return
	*/
	function getShareConfig($url){
		$config = $this->getWechatInfo();
		
		$appid = $config['appid']; 
		$token = $config['access_token'];
		
		//获取 Ticket
		$url2 = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='
			.$token.'&type=jsapi';
			
		$data = json_decode(Tools::http_get($url2),true);
		
		$ticket = $data['ticket'];
		$parm = array(
			'jsapi_ticket'	=>	$ticket,
			'noncestr'	=>	$this->getNoncestr(),
			'timestamp'	=>	time(),
			'url'	=>	$url, 
		);
		
		$str = array();
		foreach($parm as $k => $v){
			$str[] = $k.'='.$v;
		}
		$string = implode('&',$str); 
		
		//生成签名字符串
		$parm['signature'] = sha1($string);
		
		$parm['appid'] = $appid;
		return $parm;
	}
	
	/**
	* 获取随机密码串
	* @param Int $length 长度
	* @return
	*/
	function getNoncestr($length=16){
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for($i = 0; $i < $length; $i++)
		{
			$str .= $chars[mt_rand(0, strlen($chars) - 1)];
		}
		return $str;
	}
	
	/**
	* 执行Post请求
	* @param Sring $service_name 服务名称
	* @param Max $parm 请求参数
	* @return
	*/
	function doServicePost($service_name,$parm){
		//获取系统参数
		$sysparm = $this->initServiceParm($service_name);
		//合并系统参数与业务参数
		$sysparm = array_merge($sysparm,$parm);	 
		$url = APIURL::_getServiceUrl();
		$data = json_decode(Tools::http_post($url,$sysparm),true);
		return $data;
	}
	
	/**
	* 初始化系统参数
	* @param String $service_name 服务名称
	* @return
	*/
	function initServiceParm($service_name){
		$tokeninfo = $this->getToken();
		$parm = array(
			'access_token'=>$tokeninfo['accessToken'],
			'service_name'=>$service_name, 
			'timestamp'=>time(),
			'salt'=>0,
		);
		$parm['sign'] = $this->getSign($parm);
		return $parm;
	}
	
	/**
	* 获取授权地址
	* @param String $callback 回调地址
	* @param String $scope 获取信息类别  snsapi_base:只获取OPENID snsapi_userinfo:获取用户详细信息
	* @return
	*/
	function getOauthUrl($callback,$scope='snsapi_userinfo'){
		//1.获取到APPID  通过OPENAPI获取到
		$config = $this->getWechatInfo();  
		
		if($scope!='snsapi_userinfo') $scope = 'snsapi_base' ;
		$appid = $config['appid'];  

		//2.回调地址
		// h5yx.st1.bl.com
		$url = 'http://'.$config['domain'].$callback;
		
		//3.生成授权地址
		$oauthurl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid
					.'&redirect_uri='.urlencode($url)
					.'&response_type=code&scope='.$scope.'&state=123#wechat_redirect';
		
		//$this->_D($oauthurl);
		
		return $oauthurl;
	}
	
	/**
	* 获取授权回调的信息
	* @return
	*/
	function oauthback(){
		$code = $_GET['code'];
		$config = $this->getWechatInfo();  
		$appid = $config['appid'];
		$appsecret = $config['appsecret'];
		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='
				.$appid.'&secret='.$appsecret
				.'&code='.$code.'&grant_type=authorization_code'; 
		$rs = json_decode(Tools::http_get($url),true);
		//获取用户详细信息
		if($rs['scope']=='snsapi_userinfo'){
			$url2 = 'https://api.weixin.qq.com/sns/userinfo?access_token='
				.$rs['access_token'].'&openid='.$rs['openid'].'&lang=zh_CN';
			$rs2 =  json_decode(Tools::http_get($url2),true); 
			
			return $rs2;
		}
		//获取用户简单信息 只获取到OPENID
		else{
			return $rs; 
		}
	}
	
	function getuserInfo($openid,$token){
		$url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
		$data = file_get_contents($url);
		return json_decode($data,true);
	}
	
	/**
	* 获取有关微信的所有配置信息
	* @return
	*/
	function getWechatInfo(){
		//取缓存
		$config = $this->getConfigFromCache();
		$config = null;
		if(!$config){
			//如果取缓存失败，重新从服务器上获取
			$config = $this->getConfigFromUrl(); 
			$this->setConfigToCache($config);
		}
		//$this->_D($config);
		return $config;
	}
	
	/**
	* 从服务器上获取 Wechat 配置信息
	* @return
	*/
	function getConfigFromUrl(){
		$url = APIURL::_getServiceUrl();
		$tokeninfo = $this->getToken(); 
		$parm = array(
			'access_token'=>$tokeninfo['accessToken'],
			'service_name'=>'bl.social.wechat.getaccount', 
			'timestamp'=>time(),
			'salt'=>WX_Config::$api_salt,
		);
		$parm['sign'] = $this->getSign($parm);
		 
		$data = array( 
			'rid'	=>	WX_Config::$api_rid,
			'userid'	=>	WX_Config::$api_userid,
			'password'	=>	WX_Config::$api_password,
		); 
		
		$parm = array_merge($parm,$data);  
		$data = json_decode(Tools::http_post($url,$parm),true);   
		
		if($data['errcode']!=0){
			$this->_D($data);
			return false;
		}
		//$this->_D($data);
		return $data['data'];
	}
	
	
	/**
	* 获取Token
	* @return
	*/
	function getToken(){
		$token = $this->getCache();
		$token = '';
		if(!$token){ 
			$token = $this->getNewToken();
			$this->setCache($token);
		}
		//$this->_D($token);
		return $token;
	}
	
	/**
	* 去API请求Token
	* @return
	*/
	function getNewToken(){
		$url =  APIURL::_getToekn();
		$parm = array(
			'grant_type'=>WX_Config::$api_grant_type,
			'appid'=>WX_Config::$api_appid,
			'secret'=>WX_Config::$api_secret,
			'timestamp'=>time(), 
			'salt'=>WX_Config::$api_salt,
		); 
		$parm['sign'] = $this->getSign($parm); 
		//$this->_D($parm,false);
		$data =  json_decode(Tools::http_post($url,$parm),true);
		//$this->_D($data);
		return $data;
	}
	
	/**
	* 获取Sign加密
	* @param undefined $parm
	* @return
	*/
	function getSign($parm){ 
		$tarr = array();
		foreach($parm as $k => $v){
			$tarr[] = $v;
		}
		$string = implode('',$tarr);
		//$this->_D($string,false);
		return md5($string);
	}
	
	/************************** 以下缓存只是记录在SESSION中 **************************/
	/**
	* 缓存accessToken 
	*/
	function getCache(){
		if(empty($_SESSION)) return false;
		if(!isset($_SESSION['token_data'])) return false;
		$token = $_SESSION['token_data'];
		if($token['endtime']<=time()) return false; 
		return $token;
	}
	
	function setCache($val){
		$data = array(
			'accessToken' => $val['accessToken'],
			'endtime' => time()+$val['expiresIn'],
		);
		$_SESSION['token_data'] = $data;
		return true;
	}
	
	function cleanCache(){
		$_SESSION['token_data'] = null;
		unset($_SESSION['token_data']);
	}
	
	/**
	* 缓存微信所有配置
	*/
	function getConfigFromCache(){
		if(empty($_SESSION)) return false;
		if(!isset($_SESSION['config_data'])) return false;
		$config = $_SESSION['config_data'];
		if($config['expire_access']<=time()) return false; 
		return $config;
		return false;
	}
	
	function setConfigToCache($data){
		$_SESSION['config_data'] = $data;
		return false;
	}
	 
}